package com.shmet.tool.localcall.frame.register;

import com.shmet.tool.localcall.frame.factory.BizProxyFactory;
import com.shmet.tool.localcall.frame.service.BizService;
import com.shmet.tool.localcall.frame.service.BizServiceProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author shmet
 * @date 2022/7/8 18:26
 * @desc Springboot扩展bean初始化后置扩展复写，注册实现基接口的service实现，约定按照beanName名称规则识别使用
 */
@Component
public class BizRegister implements BeanPostProcessor, ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private static final Logger logger = LoggerFactory.getLogger(BizRegister.class);
    private static volatile Map<String, Object> FORM_SDK_BEAN_MAP = new ConcurrentHashMap();

    @Override
    public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
        // 存放的常量池
        Class<?> clazz = bean.getClass();
        if (BizServiceProxy.class.isAssignableFrom(clazz)) {
            return new BizProxyFactory(bean).getProxy();
        } else if (BizService.class.isAssignableFrom(clazz)) {
            BizRegister.setServiceBean(beanName, bean);
            return bean;
        }
        return bean;
    }

    public static Map<String, Object> getServiceBeanMap() {
        return FORM_SDK_BEAN_MAP;
    }

    public static Object getServiceBean(String name) {
        return FORM_SDK_BEAN_MAP.get(name);
    }

    public static void setServiceBean(String name, Object object) {
        FORM_SDK_BEAN_MAP.put(name, object);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BizRegister.applicationContext = applicationContext;
    }
}
